const LRTool = require("../tools/lr-tool");
const ReportTool = require("../tools/report-tool")
const Reporter = require('lighthouse/lighthouse-core/report/report-generator');
const fs = require('fs-extra');

/**
 * 测试运行
 * @param {*} url 被测网址
 * @param {*} config lighthouse config
 * @param {*} singleReportTitle 单次lighthouse测试的报告标题
 */
async function lr_run(url, config, singleReportTitle) {
    try {
        let case_report_path = "./report/cases-report/";
        let result = await LRTool.launchChromeAndRunLighthouse(url, config);
        let report = await ReportTool.generateHtmlReport(result);
        let timestamp = new Date().getTime();
        let singleReportName = `${singleReportTitle}@${timestamp}`;
        await ReportTool.printeHtmlReport(report, case_report_path, singleReportName);
        let indicator = LRTool.getIndicator(result);
        return { indicator, singleReportName };
    } catch (error) {
        console.log("lighthouse 测试出错", error);
    }
}

/**
 * 输出总报告
 * @param {*} summaryIndicator 
 * @param {*} template_name 
 */
async function outputSummaryReport(summaryIndicator, title) {
    try {
        let template = await fs.readFileSync("./report/template/template-makeblock.html", 'utf-8');
        let summary_report = Reporter.replaceStrings(template, [{
            search: "%%REPORT_TITLE%%",
            replacement: title
        }, {
            search: "%%SUMMARY_INDICATOR%%",
            replacement: JSON.stringify(summaryIndicator)
        }])
        let timestamp = new Date().getTime();
        ReportTool.writeReport(`./report/summary-report/${title}@${timestamp}.html`, summary_report)
    } catch (error) {
        console.log("生成总报告出错", error );
    }
}

module.exports = {
    lr_run,
    outputSummaryReport
}